<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable no-unused-vars -->
<script setup>
import axios from 'axios'
import { reactive, computed, onMounted, getCurrentInstance, watch, ref } from 'vue'
import { useRoute } from 'vue-router'
import { LZ4, decompressLZ4 } from '@/utils/wasm'
import { Markdown, emitter } from '@/utils'
import { AlexMsg } from '@2473o/alexui'
import { getArticleDetail } from '@/utils/api/article'

const app = getCurrentInstance()

const { dayjs } = app.appContext.app.config.globalProperties
const route = useRoute()
const article_detail = ref(null)

const loadWasm = async () => {
  await LZ4()
  console.log('WASM module LZ4 loaded')
}

// 网络加载文件
const loadArticle = async (url) => {
  let response
  // let response = await axios.get(url, { responseType: 'arraybuffer' })
  try {
    response = await axios.get(url, { responseType: 'arraybuffer' })
  } catch (e) {
    _data.err = e
  }
  if (!response.data) {
    return
  }

  try {
    let decompressedData = await decompressLZ4(response.data)
    _data._markdown = new TextDecoder().decode(decompressedData)
    let _md = new Markdown(_data._markdown)
    _data.article = _md.content()
    emitter.emit('on-toc-list', _md.toc_list())
    _data.title = _md.title()
  } catch (error) {
    _data.err = error
  }
}

const _data = reactive({
  article: '',
  _markdown: '',
  title: {
    title: null,
    uuid: null
  },
  _list: [],
  err: '',
  wasmInitialized: false
})

watch(
  () => _data.err,
  (newValue) => {
    AlexMsg({
      text: newValue,
      type: 'error'
    })
  }
)

const articleID = computed(() => {
  if (route.meta && route.meta.params && route.meta.params.id) {
    return route.meta.params.id
  } else if (route.params && route.params.id) {
    return route.params.id
  } else {
    return 'error'
  }
})

onMounted(async () => {
  await loadWasm()

  article_detail.value = await getArticleDetail(articleID.value)

  await loadArticle(article_detail.value.articleContext)
})
</script>

<template>
  <h1 class="article-title h2 mb-2" :id="_data.title.uuid">{{ _data.title.title }}</h1>
  <ul class="article-info d-flex text-gray reset-ul m-0">
    <li>
      <i class="czs-time" style="margin-right: 0.2rem"></i>
      <time v-if="article_detail" :title="article_detail.updateTime">
        {{ dayjs(new Date(article_detail.updateTime)).fromNow() }}</time
      >
    </li>
    <!-- <li class="c-hand">
      <i class="czs-heart"></i>
      <span>44</span>
    </li> -->
  </ul>
  <div class="divider"></div>
  <div class="article-content" v-html="_data.article"></div>
</template>

<style scoped></style>
